package com.rules.admin.utils;

import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.apache.commons.codec.digest.DigestUtils;
import org.codehaus.groovy.runtime.InvokerHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GroovyUtils<T> {
   private static final GroovyShell GROOVY_SHELL = new GroovyShell();
   private static final Map<String, Script> SCRIPT_CACHE = new ConcurrentHashMap();

   public static <T> T invokeWithCache(String scriptText, String function, Object... objects) {
      String cacheKey = DigestUtils.md5Hex(scriptText);
      Script script;
      if (SCRIPT_CACHE.containsKey(cacheKey)) {
         script = (Script)SCRIPT_CACHE.get(cacheKey);
      } else {
         script = GROOVY_SHELL.parse(scriptText);
         SCRIPT_CACHE.put(cacheKey, script);
      }

      return (T) InvokerHelper.invokeMethod(script, function, objects);
   }
}
